package cn.tedu._05weibo.common.exception;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.UserException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
//    @ExceptionHandler
//    public JsonResult doHandleException(Throwable e) {
//
//        String message = e.getMessage();
//        log.error("Throwable" + message);
//
//        return new JsonResult(StatusCode.THROWABLE_ERROR, message);
//    }

//    @ExceptionHandler
//    public JsonResult doHandleRuntimeException(RuntimeException e) {
//
//        String message = e.getMessage();
//        log.error("RuntimeException" + message);
//
//        return new JsonResult(StatusCode.OPERATION_FAIL, message);
//    }

    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException e) {

        String message = e.getMessage();
        log.error("IllegalArgumentException" + message);

        return new JsonResult(StatusCode.OPERATION_FAIL, message);
    }

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e) {

        String message = e.getFieldError().getDefaultMessage();

        log.error("MethodArgumentNotValidException" + message);

        return new JsonResult(StatusCode.PARAM_ERROR, message);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e){
        String message = e.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException" + message);
        return new JsonResult(StatusCode.PARAM_ERROR, message);
    }

}
